﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Data;
using saveimagetodatabase;
using System.Data.SqlClient;
using System.ServiceModel;

namespace WcfServiceLibrary2
{
    [DataContract]
   public class Image
    {
        [DataMember]
        public int Id{get;set;}
        [DataMember]
        public byte[] ImageData{get;set;}
        public Image(DataRow row)
        {
            this.Id = row.IsNull("id")?0:int.Parse(row["id"].ToString());
            this.ImageData =row.IsNull("image")?null: (byte[])row["image"];
        }
        public static void ImageInsert(Image newImage)
        {
           try
           {
               SqlQuery sql = new SqlQuery();
               List<SqlParameter> listPara = new List<SqlParameter>();
               listPara.Add(new SqlParameter("@image", newImage.ImageData));
               sql.ExcuteProceduteCommand("spImageInsert", listPara);
           }
           catch (System.Exception ex)
           {
               throw new FaultException(ex.Message);
           }
        }
        public static Image ImageGetById(int id)
        {
           try
           {
               SqlQuery sql = new SqlQuery();
               List<SqlParameter> list = new List<SqlParameter>();
               list.Add(new SqlParameter("@id", id));
               DataTable data = sql.ExcuteProcedute("spImageGetById", list);
               if (data.Rows.Count==0)
               {
                   return null;
               }
               else
               {
                   return new Image(data.Rows[0]);
               }
           }
           catch (System.Exception ex)
           {
               throw new FaultException(ex.Message);
           }
        }
        public static List<Image>ImageGetAll()
        {
            try
            {
                SqlQuery sql = new SqlQuery();

                DataTable data = sql.ExcuteProcedute("spImageGetAll", null);
                if (data.Rows.Count == 0)
                {
                    return null;
                }
                else
                {
                    List<Image> imageList = new List<Image>();
                    foreach (DataRow row in data.Rows)
                    {
                        imageList.Add(new Image(row));
                    }
                    return imageList;
                }
            }
            catch (System.Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }
    }
}
